package com.sunlands.deskmate.message.handler.mq;

import com.rabbitmq.client.Channel;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.utils.Idempotent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;

/**
 * @Author: anjunling@sunlands.com
 * @Description:
 * @Date: Create in 20:38 2018/6/5
 * @Modified By:
 */
@Slf4j
public abstract class AbstractInboundMessageWorker {

    @Autowired
    protected Idempotent idempotent;

    protected void handle(boolean success, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        if (success) {
            log.debug("rabbitmq message ack message = {}", message);
            //消费消息完成
            channel.basicAck(deliveryTag, false);
        } else {
            log.debug("rabbitmq message reject message = {}", message);
            //消息重回队列
            channel.basicReject(deliveryTag, true);
        }
    }

    protected String checkMsg(Messages jsonObject) {
//        String msgType = jsonObject.getString(MessageConstants.MSGTYPE);
//        if (MessageEnum.TEXT.type.equalsIgnoreCase(msgType) ||
//                MessageEnum.IMAGE.type.equalsIgnoreCase(msgType) ||
//                MessageEnum.AUDIO.type.equalsIgnoreCase(msgType) ||
//                MessageEnum.VIDEO.type.equalsIgnoreCase(msgType) ||
//                MessageEnum.EVENT.type.equalsIgnoreCase(msgType) ||
//                MessageEnum.CARD.type.equalsIgnoreCase(msgType)) {
//            //检查数据
//            return handler.check(jsonObject);
//        } else if (MessageEnum.SYS.type.equalsIgnoreCase(msgType)) {
//            //检查数据
//            String type = jsonObject.getJSONObject(MessageConstants.CONTENT).getString(MessageConstants.SYSTEM_TYPE);
//            String uniqueKey = jsonObject.getString(MessageConstants.REQUEST_ID);
//            if (StringUtils.isEmpty(type)) {
//                return "type不能为空";
//            }
//            if (StringUtils.isEmpty(uniqueKey)) {
//                return "uniquekey不能为空";
//            }
//            return null;
//        }
        return null;
    }

    protected void checkCause(String checkDesc, String message, Message mqMessage, Channel mqChannel) throws IOException {
        if (checkDesc != null) {
            log.warn("{} messages invalid {}", checkDesc, message);
            handle(true, mqMessage, mqChannel);
        }
    }

}
